//
//  SetPersonInfoViewController.m
//  ShrimpCrowdordering
//
//  Created by 郑洲 on 2018/8/20.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "SetPersonInfoViewController.h"

#import "TabBarViewController.h"

#import <AFNetworking.h>

@interface SetPersonInfoViewController ()<UITextFieldDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>{
    UIButton *shadowBtn;
}

@property (nonatomic,strong) UIButton *completeBtn;
@property (nonatomic,strong) UIImageView *headImage;
@property (nonatomic,strong) UIImage *chooseImage;

@property (nonatomic, strong) UIImagePickerController *pickerController;

@property (nonatomic, strong) UIDatePicker *dataPicker;
@property (nonatomic, strong) UIView *pickViewToobar;//pickview的完成工具条

@property (nonatomic, copy)   NSString *selectTime;

@end

@implementation SetPersonInfoViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setUI];
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.pickerController = [[UIImagePickerController alloc] init];
    self.pickerController.delegate = self;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (void)setUI {
    UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, STATUS_BAR_HEIGHT, ScreenX375(44), ScreenX375(44))];
    [backBtn setImage:ImageWithName(@"返回") forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backBtn];
    
    self.headImage = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - ScreenX375(81)) / 2, ScreenX375(44) + STATUS_BAR_HEIGHT, ScreenX375(81), ScreenX375(81))];
    self.headImage.image = ImageWithName(@"头像");
    self.headImage.userInteractionEnabled = YES;
    self.headImage.layer.cornerRadius = ScreenX375(40.5);
    self.headImage.clipsToBounds = YES;
    [self.view addSubview:self.headImage];
    
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeImage)];
    [self.headImage addGestureRecognizer:tapGR];
    
    NSArray *noteArr = @[@"个人昵称",@"个人签名",@"个人性别",@"个人年龄"];
    NSArray *placeArr = @[@"请输入昵称",@"请输入个人签名",@"请选择",@"请选择"];
    for (int i = 0; i < 4; i++) {
        UILabel *leftLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, ScreenX375(76), ScreenX375(37))];
        leftLabel.text = noteArr[i];
        leftLabel.textColor = REXADECIMALCOLOR(@"#212121");
        leftLabel.font = Kfont(15);
        
        UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(ScreenX375(37), ScreenX375(167) + STATUS_BAR_HEIGHT + i * ScreenX375(68), SCREEN_WIDTH - ScreenX375(74), ScreenX375(37))];
        textField.font = Kfont(15);
        textField.placeholder = placeArr[i];
        textField.leftView = leftLabel;
        textField.clearsOnBeginEditing = NO;
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        textField.leftViewMode = UITextFieldViewModeAlways;
        textField.returnKeyType = UIReturnKeyDone;
        textField.delegate = self;
        textField.tag = 100 + i;
        [textField addTarget:self action:@selector(changeText) forControlEvents:UIControlEventEditingChanged];
        [self.view addSubview:textField];
        
        if (i == 2) {
            UIButton *selectSex = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - ScreenX375(74), ScreenX375(37))];
            [selectSex addTarget:self action:@selector(selectSex) forControlEvents:UIControlEventTouchUpInside];
            [textField addSubview:selectSex];
        }else if (i == 3) {
            UIButton *selectTime = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - ScreenX375(74), ScreenX375(37))];
            [selectTime addTarget:self action:@selector(selectTimeAction) forControlEvents:UIControlEventTouchUpInside];
            [textField addSubview:selectTime];
        }
        
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(ScreenX375(37), ScreenX375(204) + STATUS_BAR_HEIGHT + i * ScreenX375(68), SCREEN_WIDTH - ScreenX375(74), 0.5)];
        line.backgroundColor = LineColor;
        [self.view addSubview:line];
    }
    
    self.completeBtn = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - ScreenX375(193)) / 2, ScreenX375(460) + STATUS_BAR_HEIGHT, ScreenX375(193), ScreenX375(103))];
    [self.completeBtn setTitle:@"提交" forState:UIControlStateNormal];
    self.completeBtn.titleLabel.font = Kfont(18);
    [self.completeBtn setTitleColor:REXADECIMALCOLOR(@"#ffffff") forState:UIControlStateNormal];
    self.completeBtn.titleEdgeInsets = UIEdgeInsetsMake(-5, 0, 5, 0);
    [self.completeBtn setBackgroundImage:ImageWithName(@"按钮1") forState:UIControlStateNormal];
    [self.completeBtn addTarget:self action:@selector(completeClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.completeBtn];
}

- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)completeClick {
    NSData *head = [[NSData alloc]init];
    if (_chooseImage) {
        head = UIImageJPEGRepresentation(_chooseImage, 0.3f);
    }else {
        [HttpManager showNoteMsg:@"请设置头像"];
        return;
    }
    NSArray *noteArr = @[@"请输入昵称",@"请输入个性签名",@"请选择性别",@"请选择出生日期"];
    for (int i = 0; i < 4; i++) {
        UITextField *textFiled = [self.view viewWithTag:100 + i];
        if (textFiled.text.length == 0) {
            [HttpManager showNoteMsg:noteArr[i]];
            return;
        }
    }
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 15.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/JavaScript",@"text/html",@"text/plain", nil];
    [manager POST:[NSString stringWithFormat:@"%@api/upload",REQUESTHEADER] parameters:@{@"attach":@[head]} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:head name:@"attach" fileName:@"attach.jpg" mimeType:@"image/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *status = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        if ([status isEqualToString:@"200"]) {
            NSString *headStr = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"pics"][0]];
            
            NSDictionary *parameter = @{@"nickName":[(UITextField *)[self.view viewWithTag:100] text],
                                        @"sex":[(UITextField *)[self.view viewWithTag:102] text],
                                        @"birthday":[(UITextField *)[self.view viewWithTag:103] text],
                                        @"pic":headStr,
                                        @"intro":[(UITextField *)[self.view viewWithTag:101] text],
                                        @"phone":self.phone,
                                        @"password":self.password};
            if (self.openId.length > 0) {
                parameter = @{@"nickName":[(UITextField *)[self.view viewWithTag:100] text],
                              @"sex":[(UITextField *)[self.view viewWithTag:102] text],
                              @"birthday":[(UITextField *)[self.view viewWithTag:103] text],
                              @"pic":headStr,
                              @"intro":[(UITextField *)[self.view viewWithTag:101] text],
                              @"phone":self.phone,
                              @"password":self.password,
                              @"openId":self.openId
                              };
            }
            [HttpManager postHttpRequestByPost:[NSString stringWithFormat:@"%@api/register",REQUESTHEADER] andParameter:parameter success:^(id successResponse) {
                NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
                [HttpManager hideWait];
                if ([status isEqualToString:@"200"]) {
                    [HttpManager showNoteMsg:@"注册成功"];
                    [self login];
                }else {
                    [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"message"]]];
                }
            } andFailure:^(id failureResponse) {
                [HttpManager hideWait];
                [HttpManager showNoteMsg:@"注册失败"];
            }];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [HttpManager hideWait];
        [HttpManager showNoteMsg:@"上传失败"];
    }];
}

- (void)login {
    [HttpManager showWaitMsg:@"自动登录中"];
    NSString *url = [NSString stringWithFormat:@"%@api/login",REQUESTHEADER];
    NSDictionary *parameter = @{@"phone":self.phone,@"password":self.password};
    [HttpManager postHttpRequestByGet:url andParameter:parameter success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
        [HttpManager hideWait];
        if ([status isEqualToString:@"200"]) {
            NSString *authorization = [NSString stringWithFormat:@"%@",successResponse[@"data"][@"Authorization"]];
            kNSUDefaultSaveVauleAndKey(authorization, @"Authorization");
            
            NSString *userId = [NSString stringWithFormat:@"%@",successResponse[@"data"][@"user"][@"id"]];
            kNSUDefaultSaveVauleAndKey(userId, @"userId");
            
            NSString *nickName = [NSString stringWithFormat:@"%@",successResponse[@"data"][@"user"][@"nickName"]];
            kNSUDefaultSaveVauleAndKey(nickName, @"nickName");
            
            NSString *intro = [NSString stringWithFormat:@"%@",successResponse[@"data"][@"user"][@"intro"]];
            kNSUDefaultSaveVauleAndKey(intro, @"intro");
            
            NSString *pic = [NSString stringWithFormat:@"%@",successResponse[@"data"][@"user"][@"pic"]];
            kNSUDefaultSaveVauleAndKey(pic, @"pic");
            
            NSString *inviteCode = [NSString stringWithFormat:@"%@",successResponse[@"data"][@"user"][@"inviteCode"]];
            kNSUDefaultSaveVauleAndKey(inviteCode, @"inviteCode");
            
            NSString *birthday = [NSString stringWithFormat:@"%@",successResponse[@"data"][@"user"][@"birthday"]];
            kNSUDefaultSaveVauleAndKey(birthday, @"birthday");
            
            NSString *qrCode = [NSString stringWithFormat:@"%@",successResponse[@"data"][@"user"][@"qrCode"]];
            kNSUDefaultSaveVauleAndKey(qrCode, @"qrCode");
            
            NSString *sex = [NSString stringWithFormat:@"%@",successResponse[@"data"][@"user"][@"sex"]];
            kNSUDefaultSaveVauleAndKey(sex, @"sex");
            
            [kUserDefaults synchronize];
            
            kKeyWindow.rootViewController = [[TabBarViewController alloc] init];
        }else {
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"message"]]];
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
    }];
}

- (void)changeText {
    for (int i = 0; i < 4; i++) {
        UITextField *textFiled = [self.view viewWithTag:100 + i];
        if (textFiled.text.length == 0) {
            [self.completeBtn setBackgroundImage:ImageWithName(@"按钮1") forState:UIControlStateNormal];
            return;
        }
    }
    [self.completeBtn setBackgroundImage:ImageWithName(@"按钮2") forState:UIControlStateNormal];
}

- (void)changeImage {
    [self.view endEditing:YES];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *send = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        self.pickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
        self.pickerController.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        [self presentViewController:self.pickerController animated:YES completion:nil];
    }];
    UIAlertAction *get = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        self.pickerController.allowsEditing = YES;
        [self presentViewController:self.pickerController animated:YES completion:nil];
    }];
    
    [alert addAction:cancel];
    [alert addAction:send];
    [alert addAction:get];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    _headImage.image = image;
    _chooseImage = image;
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self.pickerController dismissViewControllerAnimated:YES completion:nil];
}

- (void)selectSex {
    [self.view endEditing:YES];
    UITextField *sexField = [self.view viewWithTag:102];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *boy = [UIAlertAction actionWithTitle:@"男" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        sexField.text = @"男";
        [self changeText];
    }];
    UIAlertAction *giel = [UIAlertAction actionWithTitle:@"女" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        sexField.text = @"女";
        [self changeText];
    }];
    [alert addAction:boy];
    [alert addAction:giel];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)selectTimeAction {
    [self.view endEditing:YES];
    if (!shadowBtn) {
        shadowBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        shadowBtn.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
        [shadowBtn addTarget:self action:@selector(hiddenPickView) forControlEvents:UIControlEventTouchUpInside];
        shadowBtn.hidden = YES;
        [self.view addSubview:shadowBtn];
    }
    if (!_pickViewToobar) {
        [self setPickerToobar];
    }
    if (!_dataPicker) {
        _dataPicker = [[UIDatePicker alloc] init];
        _dataPicker.frame = CGRectMake(0,CGRectGetMaxY(_pickViewToobar.frame), SCREEN_WIDTH, SCREEN_WIDTH / 375 * 260 - 44); // 设置显示的位置和大小
        _dataPicker.date = [NSDate date]; // 设置初始时间
        _dataPicker.backgroundColor = [UIColor whiteColor];
        _dataPicker.timeZone = [NSTimeZone timeZoneWithName:@"GTM+8"]; // 设置时区，中国在东八区
        _dataPicker.datePickerMode = UIDatePickerModeDate; // 设置样式
        [_dataPicker addTarget:self action:@selector(datePickerValueChanged:) forControlEvents:UIControlEventValueChanged]; // 添加监听器
        [self.view addSubview:_dataPicker];
    }
    //判断pickerView的位置
    if (_dataPicker.frame.origin.y == SCREEN_HEIGHT+44) {
        
        [UIView animateWithDuration:0.3 animations:^{
            self->shadowBtn.hidden = NO;
            self.dataPicker.frame = CGRectMake(0, SCREEN_HEIGHT - (SCREEN_HEIGHT + NAVIGATION_BAR_HEIGHT) / 2.5 + 44, SCREEN_WIDTH, (SCREEN_HEIGHT + NAVIGATION_BAR_HEIGHT) / 2.5 - 44);
            self.pickViewToobar.frame = CGRectMake(0,CGRectGetMinY(self.dataPicker.frame)-44, SCREEN_WIDTH, 44);
            
        }];
        
    }else{
        
        [UIView animateWithDuration:0.3 animations:^{
            self->shadowBtn.hidden = YES;
            self.pickViewToobar.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 44);
            self.dataPicker.frame = CGRectMake(0, CGRectGetMaxY(self.pickViewToobar.frame), SCREEN_WIDTH, (SCREEN_HEIGHT + NAVIGATION_BAR_HEIGHT) / 2.5 - 44);
        }];
    }
}

//点击pickView的工具条操作按钮
- (void)pickViewOperateClick:(UIButton *)sender{
    
    if (sender.tag == 1) {
        //完成
        [self hiddenPickView];
        UITextField *ageField = [self.view viewWithTag:103];
        ageField.text = _selectTime;
        [self changeText];
    }else{
        //取消
        [self hiddenPickView];
        _selectTime = @"";
    }
}

- (void)datePickerValueChanged:(UIDatePicker *) sender {
    
    NSDate *select = [sender date]; // 获取被选中的时间
    NSDateFormatter *selectDateFormatter = [[NSDateFormatter alloc] init];
    selectDateFormatter.dateFormat = @"yyyy-MM-dd"; // 设置时间和日期的格式
    _selectTime = [selectDateFormatter stringFromDate:select]; // 把date类型转为设置好格式的string类型
}

- (void)setPickerToobar {
    //工具条
    _pickViewToobar = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 44)];
    _pickViewToobar.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_pickViewToobar];
    
    for (int i = 0; i < 2; i++) {
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, i * 43.5, SCREEN_WIDTH, 0.5)];
        line.backgroundColor = LineColor;
        [_pickViewToobar addSubview:line];
    }
    
    UIButton *cancleBtn = [[UIButton alloc]initWithFrame:CGRectMake(15, 0, 40, _pickViewToobar.frame.size.height)];
    [cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancleBtn setTitleColor:ThemeColor forState:UIControlStateNormal];
    [cancleBtn addTarget:self action:@selector(pickViewOperateClick:) forControlEvents:UIControlEventTouchUpInside];
    [_pickViewToobar addSubview:cancleBtn];
    
    UIButton *achiveBtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 50, 0, 40, _pickViewToobar.frame.size.height)];
    [achiveBtn setTitle:@"完成" forState:UIControlStateNormal];
    achiveBtn.tag = 1;
    [achiveBtn setTitleColor:ThemeColor forState:UIControlStateNormal];
    [achiveBtn addTarget:self action:@selector(pickViewOperateClick:) forControlEvents:UIControlEventTouchUpInside];
    [_pickViewToobar addSubview:achiveBtn];
}


- (void)hiddenPickView{
    [UIView animateWithDuration:0.3 animations:^{
        self->shadowBtn.hidden = YES;
        self.pickViewToobar.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 44);
        self.dataPicker.frame = CGRectMake(0, CGRectGetMaxY(self.pickViewToobar.frame), SCREEN_WIDTH, (SCREEN_HEIGHT + NAVIGATION_BAR_HEIGHT) / 2.5);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
